// 地址相关方法
import AreaData from '@constants/area';
/**
 * 处理搜索后的结果名称
 * @param {String} name 名称
 * @param {String} str 搜索字符
 */
export const dealSearchName = (name, str) => {
    const arr = name.split(str);
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        if (item) {
            result.push({
                value: item,
                type: 'normal',
                isTheme: false,
            });
        }
        if (i < arr.length - 1) {
            result.push({
                value: str,
                type: 'red',
                isTheme: true,
            });
        }
    }
    return result;
};

/**
 * 处理距离数据
 * @param {Number} distance 距离值
 */
export const dealDistance = (distance) => {
    if (!distance) {
        return '';
    }
    if (distance < 1) {
        return `距您${distance * 1000}m`;
    }
    if (distance > 1) {
        return `距您${distance.toFixed(2)}km`;
    }
    return `距您${parseInt(distance)}m`;
};

/**
 * 获取定位所在的省、市、区相应的代码，搜索前置条件，显示地址
 * @param {String} address 通过定位获取到的地址
 */
export const getDefaultValue = (address) => {
    const result = '330100'; // 默认返回 '杭州市' 的编码
    if (!address) {
        return {
            code: '330100',
            searchVal: '浙江省杭州市',
            showVal: '杭州市',
        };
    }
    const reg = /.+?(省|市|自治区|自治州|县|区)/g;
    const vals = address.match(reg);
    const last_val = vals[vals.length - 1];
    const { province_list, city_list, county_list } = AreaData;
    const v_1 = returnKey(province_list, last_val);
    const v_2 = returnKey(city_list, last_val);
    const v_3 = returnKey(county_list, last_val);
    // return v_1 || v_2 || v_3 || result;
    return {
        code: v_1 || v_2 || v_3 || '330100',
        searchVal: `${province_list}${city_list}${county_list}`,
        showVal: last_val,
    };
};

const returnKey = (obj, val, compare = (a, b) => a === b) => {
    return Object.keys(obj).find(k => compare(obj[k], val));
};

/**
 * 通过id，获取地址信息
 * @param {Array} arr 地址列表数组
 * @param {Number} id id
 */
export const getItemAddressInfo = (arr, id) => {
    return arr.filter(item => item.id === id)[0] || null;
};
